package com.klb.service.catalog.impl;

import com.klb.dao.impl.UserDaoImpl;
import com.klb.model.BbsUser;
import com.klb.service.catalog.RegisterServiceCatalog;
import com.klb.tools.CryptoUtils;
import com.klb.tools.Tools;

/**
 * Created by fujia on 2016/6/1.
 */
public class RegisterServiceCatalogImpl implements RegisterServiceCatalog {

    private UserDaoImpl userDao;
    private LoginServiceCatalogImpl loginServiceCatalog;


	public void setUserDao(UserDaoImpl userDao) {
		this.userDao = userDao;
	}

	public void setLoginServiceCatalog(LoginServiceCatalogImpl loginServiceCatalog) {
		this.loginServiceCatalog = loginServiceCatalog;
	}

	@Override
    public boolean registerIsSuccess(String username, String telephone, String password, String password_true) {

        /**
         * 判断不为空
         * 判断手机号是否存在
         * 获取盐值
         * 判断密码与确定密码是否正确
         * 生成复合密码
         * 存入数据库
         * 顺便登录
         * */
        if (!Tools.objectIsNullOrNot(username) && !Tools.objectIsNullOrNot(telephone) && !Tools.objectIsNullOrNot(password) && !Tools.objectIsNullOrNot(password_true)){
            if (Tools.objectIsNullOrNot(this.userDao.getUserByTelephone(telephone))){
                String salt = CryptoUtils.getSalt();
                if (password.equals(password_true)){
                    String hashPassword = CryptoUtils.getHash(password, salt);
                    if (this.userDao.addQuery(this.generateBbsUser(username, telephone, hashPassword, salt)))
                        return this.loginServiceCatalog.loginIsSuccess(telephone, password);
                }
            }
        }

        return false;
    }

    /**
     * 构建user类
     * */
    private BbsUser generateBbsUser(String username, String telephone, String password, String salt){
        BbsUser user = new BbsUser();

        user.setName(username);
        user.setTelephone(telephone);
        user.setPassword(password);
        user.setSalt(salt);
        user.setEmail("");

        return  user;
    }


}
